package com.googlecode.contests_repo.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.contests_repo.core.config.ConfigurationManager;

/**
 * Servlet for fetching zipped resources
 * 
 * @author deni
 */
@WebServlet("/fetchZipped")
public class FetchZipped extends HttpServlet {

	private static final long serialVersionUID = 1L;
       
	private String getFileName(HttpServletRequest request) {
		String[] params = {"problem", "contest", "series" };
		
		for (String s : params) {
			String val = request.getParameter(s);
			if (val != null) {
				return val;
			}
		}
		return null;
	}
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		File zip = zipResource(request);
		if (zip == null) {
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.println("You don't have permissions to download this resource!");
			return;
		}
		
		response.setContentType("application/download");
		response.setHeader( "Content-Disposition", "attachment; filename=\"" + getFileName(request) + ".zip" + "\"" );
        ServletOutputStream outputStream = response.getOutputStream ();
		
		FileInputStream in = new FileInputStream(zip);
		int length;
		byte[] buf = new byte[1 << 11];
		while ((in != null) && ((length = in.read(buf)) != -1)) 
		{
		  outputStream.write(buf,0,length);
		}
	}


	private File zipResource(HttpServletRequest request) throws IOException {
		String seriesPath = request.getParameter("series");
		String contestPath = request.getParameter("contest");
		String problemPath = request.getParameter("problem");

		String loggedInUser = (String) request.getSession().getAttribute("username");
		String repoRoot = ConfigurationManager.getInstance().getRepoRoot();
		String seriesRoot = ConfigurationManager.getInstance().getSeriesPath();
		
		// fetch series
		if (contestPath == null) {
			seriesPath = seriesRoot + File.separator + seriesPath;
			SeriesZiper ziper = new SeriesZiper();
			return ziper.fetchZipped(loggedInUser, seriesPath);
		}
		
		// fetch contest
		if (problemPath == null) {
			contestPath = repoRoot + File.separator + seriesPath + File.separator + contestPath;
			ContestZiper ziper = new ContestZiper();
			return ziper.fetchZipped(loggedInUser, contestPath);
		}
		
		// fetch problem
		problemPath = repoRoot + File.separator + contestPath + 
			File.separator + problemPath;
		ProblemZiper ziper = new ProblemZiper();
		return ziper.fetchZipped(loggedInUser, problemPath);
	}
}
